package com.chenyanqing.model.two.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.chenyanqing.model.two.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;


/**
 * 获取连接 ，保证每个线程始终用的同一个jdbc连接
 */
public class JDBCConnectionUtils {



    private DruidDataSource druidDataSource;

    private  JDBCConnectionUtils(){

    }

    private JDBCConnectionUtils(DruidDataSource druidDataSource){
        this.druidDataSource = druidDataSource;
    }

    private static JDBCConnectionUtils connectionUtils;

    /**
     * 保证单例
     * @return
     */
    public static synchronized  JDBCConnectionUtils getJDBCConnectionUtils(){
        if(connectionUtils ==null){
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUrl("jdbc:mysql://jiancai-app-cmpri-14156.rds.cn-east-beta1.internal.:3306/app?useUnicode=true&characterEncoding=utf-8&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true");
            druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            druidDataSource.setUsername("relottery_test");
            druidDataSource.setPassword("rUQyyh1234");

            connectionUtils = new JDBCConnectionUtils(druidDataSource);
            return connectionUtils;

        }
        return connectionUtils;
    }


    private ThreadLocal<Connection> conThreadLocal = new ThreadLocal<>();

    public  Connection getCurrentThreadConnection() throws SQLException {
        Connection connection = conThreadLocal.get();
        if(connection==null){
            connection = druidDataSource.getConnection();
           conThreadLocal.set(connection);
        }
        return connection;
    }
}
